<?php

namespace app\http\middleware;

use app\facade\Redis;
use app\models\User;
use app\facade\Auth as AuthHelp;
use think\Db;
use think\facade\Lang;

header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: POST, PUT, GET, OPTIONS, DELETE, HEAD, PATCH');
header("Access-Control-Allow-Headers: token, language, Origin, X-Requested-With, Content-Type, Accept");

class Auth
{
    public function handle($request, \Closure $next)
    {
//        $time = ['lt' => get_config('shutdown'), 'up' => '04:00:00'];
//        $this_time = date('H:i:s');
//        if ($this_time > $time['lt'] || $this_time < $time['up']) {
//            if ($request->header('language') == 'en-us') {
//                Lang::load('../application/lang/en-us.php');
//            } else {
//                Lang::load('../application/lang/zh-tw.php');
//            }
//            echo json_encode(['status' => 555, 'msg' => lang('结算中,暂停访问')]);
//            exit;
//        }

        $url = $request->baseUrl();
        $verify = config('auth.api');
        $hasNoneShareAuth = strpos($url,'/auth/direct_url');
        if ($hasNoneShareAuth) {
            return $next($request);
            exit;
        }
        if (!in_array($url, $verify)&&$request->header('token')) {
            $user_id = AuthHelp::get($request->header('token'));
            if (!$user_id){
                echo json_encode(['data' => null, 'msg' => '登陆已过期或失效', 'status' => 999], JSON_UNESCAPED_UNICODE);
                exit;
            }
            $user = Db::table("tb_card_shop")->where('id', $user_id)->find();
            if (!$user) {
                echo json_encode(['data' => null, 'msg' => '账号不存在', 'status' => 998], JSON_UNESCAPED_UNICODE);
                exit;
            }
            $request->user_id = $user_id;
            $request->user = $user;

        }
        return $next($request);
    }
}
